package secondriver.springsubway.example.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.util.StringUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;

import com.google.common.collect.Sets;

import secondriver.springsubway.example.bean.Post;
import secondriver.springsubway.example.dao.RedisDaoHelper;

public class RedisReadAndWriteController extends MultiActionController {

	private String viewName;

	private RedisDaoHelper redisDaoHelper;

	public ModelAndView index(HttpServletRequest request,
			HttpServletResponse response) {
		ModelAndView modeAndview = new ModelAndView(viewName);
		modeAndview.addObject("tags", redisDaoHelper.getTags());
		modeAndview.addObject("posts", redisDaoHelper.getRecentPostsList());
		return modeAndview;
	}

	public ModelAndView get(HttpServletRequest request,
			HttpServletResponse response) {
		String tag = request.getParameter("tag");
		System.out.println("get tag is " + tag);
		ModelAndView modeAndview = new ModelAndView(viewName);
		modeAndview.addObject("tags", redisDaoHelper.getTags());
		modeAndview.addObject("posts", redisDaoHelper.getPostByTag(tag, 30));
		return modeAndview;
	}

	public String save(HttpServletRequest request, HttpServletResponse response) {
		String tags = request.getParameter("tags");
		String content = request.getParameter("content");
		String description = request.getParameter("description");
		Post post = new Post();
		post.setContent(content);
		post.setDescription(description);
		if (!StringUtils.isEmpty(tags)) {
			String[] tagArray = tags.split(",");
			post.setTags(Sets.newHashSet(tagArray));
		}
		String postKey = redisDaoHelper.savePost(post);
		System.out.println("提交的" + postKey);
		return "redirect:/home";
	}

	public String getViewName() {
		return viewName;
	}

	public void setViewName(String viewName) {
		this.viewName = viewName;
	}

	public RedisDaoHelper getRedisDaoHelper() {
		return redisDaoHelper;
	}

	public void setRedisDaoHelper(RedisDaoHelper redisDaoHelper) {
		this.redisDaoHelper = redisDaoHelper;
	}

}
